import { Table, Button, Space, Tag } from 'antd';
import { scheduleService } from '../../services/schedule.service';
import { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import type { ScheduledTask } from '../../services/schedule.service';

export default function ScheduleList() {
  const [tasks, setTasks] = useState<ScheduledTask[]>([]);
  const navigate = useNavigate();

  const loadData = async () => {
    const data = await scheduleService.findAll();
    setTasks(data);
  };

  const handleDelete = async (id: string) => {
    await scheduleService.delete(id);
    loadData();
  };

  const columns = [
    {
      title: '任务名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: ScheduledTask) => (
        <Link to={`/schedule/${record.id}`}>{text}</Link>
      )
    },
    {
      title: '类型',
      dataIndex: 'task_type',
      key: 'task_type',
      render: (type: ScheduledTask['task_type']) => (
        <Tag color={type === 'data_sync' ? 'blue' : 'geekblue'}>{type}</Tag>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: ScheduledTask['status']) => (
        <Tag color={status === 'active' ? 'green' : 'orange'}>{status}</Tag>
      )
    },
    {
      title: '下次执行时间',
      dataIndex: 'next_run',
      key: 'next_run'
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: ScheduledTask) => (
        <Space>
          <Button type="link" onClick={() => navigate(`/schedule/${record.id}`)}>
            详情
          </Button>
          <Button danger onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </Space>
      )
    }
  ];

  useEffect(() => {
    loadData();
  }, []);

  return (
    <div style={{ padding: 24 }}>
      <Button 
        type="primary" 
        onClick={() => navigate('/schedule/new')}
        style={{ marginBottom: 16 }}
      >
        新建定时任务
      </Button>
      <Table
        columns={columns}
        dataSource={tasks}
        rowKey="id"
        bordered
      />
    </div>
  );
} 